def read_aligned_fasta (file_path):
    seqences = []
    current_seq = ""
    with open (file_path, "r") as f:
        for line in f:
            line = line.strip()
            if line.startswith(">"):
                if current_seq:
                    seqences.append(current_seq)
                    current_seq = ""
                continue
            current_seq += line.upper()
        if current_seq:
            seqences.append(current_seq)
    return seqences

def calculate_column_percentages(seqences):
    if not seqences:
        return []
    
    column_stats = []
    num_seqences = len (seqences)
    num_columns = len (seqences[0])
     
    for col in range(num_columns):
        aa_count = {}
        for seq in seqences:
            aa = seq[col]
            aa_count[aa] = aa_count.get(aa, 0) + 1
        total = sum(aa_count.values())
        if '-' in aa_count:
            total -= aa_count['-']
            del aa_count['-']
        if total == 0:
            continue
        percent_dict = {
            aa: (count / total) * 100 
            for aa, count in aa_count.items()
        }
        column_stats.append(percent_dict)
    
    return column_stats

file_path = "/home/zhangwt/program_text/练习3/muscle_homologs.fasta"  
sequences = read_aligned_fasta(file_path)
column_stats = calculate_column_percentages(sequences)

with open("aa_percentages.txt", "w") as f:
    for i, stats in enumerate(column_stats, start=1):
        f.write(f"第 {i} 列：\n")
        for aa, percent in stats.items():
            f.write(f"  {aa}: {percent:.2f}%\n")
    print("结果已保存到 aa_percentages.txt")